package com.example.baidumap_a.Activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.example.baidumap_a.R;
import com.example.baidumap_a.entity.Ohuang;
import com.example.baidumap_a.entity.User;
import com.example.baidumap_a.entity.UserParkOrder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;


public class PayActivity extends AppCompatActivity {
    private CheckBox checkBox;
    private int checkIds[] = {R.id.pay_checkbox_1, R.id.pay_checkbox_2, R.id.pay_checkbox_3, R.id.pay_checkbox_4, R.id.pay_checkbox_5, R.id.pay_checkbox_6, R.id.pay_checkbox_7};
    private String time[] = {"06:00", "08:00", "10:00", "12:00", "14:00", "16:00", "18:00", "20:00"};
    private String time_q[]={"06:00-08:00","08:00-10:00","10:00-12:00","12:00-14:00","14:00-16:00","16:00-18:00","18:00-20:00"};
    private Button button;
    private TextView textView;
    private int money, startTime, endTime;
    private Dialog dialogLoading;//加载对话框
    private String name;
    private int id;
    final OkHttpClient client = new OkHttpClient();
    private final static int PAY_OK = 0, PAY_ERROR = 1, PAY_MONEY = 2, BOOK_ERROR = 3, BOOK_OTHER = 4, BOOK_OK = 5, UB_OK = 6, UB_NO = 7;
    private List<UserParkOrder> mData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        Intent intent = getIntent();
        name = intent.getStringExtra("username");
        id = intent.getIntExtra("id", 0);
        initView();
        unableBookHttp();//查询不能预订的时间段
    }

    private void initView() {
        button = findViewById(R.id.pay_btn);
        textView = findViewById(R.id.pay_text_qian);
        textView.setText("您需要支付" + (0) + "元");
        for (int i = 0; i < checkIds.length; i++) {
            checkBox = findViewById(checkIds[i]);
            checkBox.setOnClickListener(CheckBoxClickListener);
        }

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<Integer> list = new ArrayList<>();

                for (int i = 0; i < checkIds.length; i++) {
                    checkBox = findViewById(checkIds[i]);

                    if (checkBox.isChecked()) {
                        list.add(i);//保存选中 i编号
                    }
                }
                int a = list.size();
                if (a == 0) {
                    Ohuang.dialogshow(PayActivity.this, "预订失败", "请选择时间段。");
                    return;
                }
                //判断保存的i的编号是否是连续的数字
                for (int i = 1; i < a; i++) {
                    if (list.get(i - 1) == (list.get(i) - 1)) {
                        continue;
                    } else {//如果不是连续的直接return
                        Ohuang.dialogshow(PayActivity.this, "预订失败", "选择的时间段不连续。");
                        return;
                    }

                }
                if (list.size() != 0) {
                    payDialogShow("预订车位", money);
                    startTime = list.get(0) * 2 + 6;
                    endTime = list.get(0) * 2 + 6 + a * 2;

                }
            }
        });
    }

    //查询不能预订时间段
    private void unableBookHttp() {

        RequestBody formBody = new FormBody.Builder()
                .add("carId", id + "")
                .build();

        final Request request = new Request.Builder()
                .url("https://d30n971042.imdo.co/park/findTimeById")
                .post(formBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                myHandler.sendEmptyMessage(UB_NO);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                ResponseBody body = response.body();
                if (body != null) {
                    String json = body.string();
                    Gson gson = new Gson();
                    Type type = new TypeToken<List<UserParkOrder>>() {
                    }.getType();
                    mData = gson.fromJson(json, type);
                    body.close();
                }
                myHandler.sendEmptyMessage(UB_OK);

            }
        });

    }


    //确认支付对话框
    @SuppressLint("SetTextI18n")
    private void payDialogShow(String a, final int b) {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_pay, null);
        final AlertDialog dialog = new AlertDialog.Builder(this, R.style.MyDialog).setView(view).create();
        TextView textView = view.findViewById(R.id.text_title_dialog_pay);
        TextView textView1 = view.findViewById(R.id.text_money_dialog_pay);
        Button button = view.findViewById(R.id.btn_pay_dialog_pay);
        ImageButton imageButton = view.findViewById(R.id.btn_x_dialog_pay);
        textView.setText(a);
        textView1.setText("￥" + b + "元");
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();//关闭对话框
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();//关闭对话框
                //再执行支付操作
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1000);
                            PostHttpRequest(b);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

                dialogLoading = Ohuang.dialogLoadingshow(PayActivity.this, "正在预订");//显示加载对话框
            }
        });
        dialog.show();//显示
        //需要先显示再设置大小
        Window window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();//获取屏幕分辨率
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;
        params.width = (int) (0.7 * screenWidth);
        window.setAttributes(params);

    }


    //checkBox监听
    View.OnClickListener CheckBoxClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            int a = 0;
            CheckBox checkBox1;
            for (int i = 0; i < checkIds.length; i++) {
                checkBox1 = findViewById(checkIds[i]);
                if (checkBox1.isChecked()) {
                    a++;
                }
            }
            money = a * 10;
            textView.setText("您需要支付" + (a * 10) + "元");
        }
    };

    public void ClosePayActivityClick(View view) {
        finish();
    }


    //付钱
    private void PostHttpRequest(int charge) {
        RequestBody formBody = new FormBody.Builder()
                .add("username", name)
                .add("money", charge + "")
                .build();

        final Request request = new Request.Builder()
                .url("https://d30n971042.imdo.co/park/payment")
                .post(formBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                myHandler.sendEmptyMessage(PAY_ERROR);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                ResponseBody body = response.body();
                if (body != null) {
                    String code = body.string();
                    if ("success".equals(code)) {
                        myHandler.sendEmptyMessage(PAY_OK);
                    } else {
                        myHandler.sendEmptyMessage(PAY_MONEY);
                    }
                    body.close();
                }

            }
        });
    }

    //预订
    private void BookParkHttp() {
//        String a,b;
//        if (startTime<10){
//            a="0"+startTime;
//        }else {
//            a=""+startTime;
//        }
//        if (endTime<10){
//            b="0"+endTime;
//        }else {
//            b=""+endTime;
//        }
        List<Integer> list=new ArrayList<>();
        for (int i = 0; i < checkIds.length; i++) {
            checkBox = findViewById(checkIds[i]);
            if (checkBox.isChecked()) {
                list.add(i);//保存选中 i编号
            }
        }
        String  time_quantum = "";
        for (Integer i:list){
            time_quantum=time_quantum+time_q[i]+",";
        }
        System.out.println(time_quantum);
        RequestBody formBody = new FormBody.Builder()
                .add("username", name)
                .add("carId", id + "")
                .add("consume", money + "")
//                .add("time_quantum", a + ":00-" + b + ":00")
                .add("time_quantum",time_quantum)
                .build();

        final Request request = new Request.Builder()
                .url("https://d30n971042.imdo.co/park/userReserve")
                .post(formBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                myHandler.sendEmptyMessage(BOOK_ERROR);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                ResponseBody body = response.body();
                if (body != null) {
                    String code = body.string();
                    if ("success".equals(code)) {
                        myHandler.sendEmptyMessage(BOOK_OK);
                    } else {
                        myHandler.sendEmptyMessage(BOOK_OTHER);
                    }
                    body.close();
                }

            }
        });
    }

    @SuppressLint("HandlerLeak")
    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case PAY_OK:
                    BookParkHttp();//预订
                    break;
                case PAY_ERROR:
                    dialogLoading.dismiss();
                    Toast.makeText(PayActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    break;

                case PAY_MONEY:
                    dialogLoading.dismiss();
                    Ohuang.dialogshow(PayActivity.this, "预订失败", "余额不足,请充值余额");
                    break;
                case BOOK_OK:
                    dialogLoading.dismiss();
                    Ohuang.dialogshow(PayActivity.this, "预订成功", "你已成功预订车位", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finish();
                        }
                    });
                    break;
                case BOOK_ERROR:
                    dialogLoading.dismiss();
                    Toast.makeText(PayActivity.this, "网络错误,请联系后台管理员", Toast.LENGTH_SHORT).show();
                    break;
                case BOOK_OTHER:
                    dialogLoading.dismiss();
                    Toast.makeText(PayActivity.this, "出现未知错误,请联系后台管理员", Toast.LENGTH_SHORT).show();
                    break;

                case UB_OK:
                    unableParkCheckBox();//使 不能预订的时间段的checkBox无效
                    break;
            }
        }
    };
    //使 不能预订的时间段的checkBox无效
    private void unableParkCheckBox(){
        if (mData != null) {
            List<Integer> listInt = new ArrayList<>();
            for (UserParkOrder us : mData) {
                String a = us.getTime_quantum();
                String s[] = a.split("-");
                int io=0, it=0;
                for (int i = 0; i < time.length; i++) {
                    if (time[i].equals(s[0])) {
                        io = i;
                    }
                }
                for (int i = 0; i < time.length; i++) {
                    if (time[i].equals(s[1])) {
                        it = i;
                    }
                }
                for (int i=io;i<it; i++){
                    listInt.add(i);
                }
            }

            for (Integer i:listInt){
                checkBox=findViewById(checkIds[i]);
                checkBox.setEnabled(false);
            }
        }
    }

}
